<?php

/** 
 * Erra_System_Action - Main class for actions
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_System_Action { 

    // Standard methods
    public static function assignTableKeyValues($arrayTable, $id, $assignation_array) {
        if (is_array($arrayTable) && is_numeric($id) && is_array($assignation_array)) {
            Erra_Core_DatabasePdo::EXECUTE('DELETE FROM ' . $arrayTable['table'] . ' WHERE '.$arrayTable['key'].'=' . $id);
            $values = array();
            foreach ($assignation_array as $agenda_id) {  
                if (is_numeric($agenda_id)) { 
                    $values[] = '(' . $id . ', ' . $agenda_id . ')';
                } 
            } 
            if (count($values)) {
                Erra_Core_DatabasePdo::EXECUTE('INSERT INTO ' . $arrayTable['table'] . '(' . $arrayTable['key'] . ', ' . $arrayTable['value'] . ') VALUES' . implode(',', $values));
            }
        }
    }

    /**
     * AdminAction::saveSql() - Saves a field in database
     *
     * @param mixed $field
     * @return
     */
    public static function saveSql(Erra_Fields_Base_Object $field) {
        //$field->setMessage(Erra_Utils_Tools::message('success', __('Data saved successfully')));
        Erra_System_Factory::saveField($field, 'SQL');
        return 'FORM_CLOSE_POPUP';
    }

    /**
     * AdminAction::saveCss() - Saves a Css and zip it
     *
     * @param mixed $field
     * @return
     */
    public static function saveCssBackup(Erra_Fields_Base_Object $field) {
        Zip(PUBLIC_ROOT . '/style', DOCUMENT_ROOT . '/backup/css/' . date('d-m-Y') . '_' . date('H-i-s') . '.backup.css.zip');
        Erra_Utils_Tools::message('success', __('CSS file saved successfully'), 'backupCss');
        return 'RELOAD';
    }

    public static function restoreCssBackup(Erra_Fields_Base_Object $field) {
        $zipFile = DOCUMENT_ROOT . '/backup/css/' . $field->hidden_field->value;
        Unzip($zipFile, PUBLIC_ROOT . '/style');
        Erra_Utils_Tools::message('success', __('CSS file restored successfully'), 'backupCss');
        return 'RELOAD';
    }

    public static function deleteCssBackup(Erra_Fields_Base_Object $field) {
        $zipFile = DOCUMENT_ROOT . '/backup/css/' . $field->hidden_field->value;
        if (file_exists($zipFile)) {
            unlink($zipFile);
        }
        Erra_Utils_Tools::message('success', __('CSS file deleted successfully'), 'backupCss');
        return 'RELOAD';
    }

    /**
     * AdminAction::saveCss() - Saves a Css and zip it
     *
     * @param mixed $field
     * @return
     */
    public static function saveSiteBackup(Erra_Fields_Base_Object $field) {
        Zip(PUBLIC_ROOT, DOCUMENT_ROOT . '/backup/site/' . date('d-m-Y') . '_' . date('H-i-s') . '.backup.site.zip');
        Erra_Utils_Tools::message('success', __('Site file saved successfully'), 'backupCss');
        return 'RELOAD';
    }

    public static function deleteSiteBackup(Erra_Fields_Base_Object $field) {
        $zipFile = DOCUMENT_ROOT . '/backup/site/' . $field->hidden_field->value;
        if (file_exists($zipFile)) {
            unlink($zipFile);
        }
        Erra_Utils_Tools::message('success', __('Site file deleted successfully'), 'backupCss');
        return 'RELOAD';
    }

    /**
     * AdminAction::saveCss() - Saves a Css and zip it
     *
     * @param mixed $field
     * @return
     */
    public static function saveSqlBackup(Erra_Fields_Base_Object $field) {
        Erra_Core_File::backupTables(DOCUMENT_ROOT . '/backup/sql/' . date('d-m-Y') . '_' . date('H-i-s') . '.backup.sql');
        Erra_Utils_Tools::message('success', __('SQL file saved successfully'), 'backupCss');
        return 'RELOAD';
    }

    public static function restoreSqlBackup(Erra_Fields_Base_Object $field) {
        $zipFile = DOCUMENT_ROOT . '/backup/sql/' . $field->hidden_field->value;
        $sqlData = file_get_contents($zipFile);
        Erra_Utils_Tools::message('success', __('SQL contents restored successfully'), 'backupCss');
        return 'RELOAD';
    }

    public static function deleteSqlBackup(Erra_Fields_Base_Object $field) {
        $zipFile = DOCUMENT_ROOT . '/backup/sql/' . $field->hidden_field->value;
        if (file_exists($zipFile)) {
            unlink($zipFile);
        }
        Erra_Utils_Tools::message('success', __('SQL file deleted successfully'), 'backupCss');
        return 'RELOAD';
    }

    /**
     * AdminAction::saveSqlReload() - Saves a field in database and reloads page
     *
     * @param mixed $field
     * @return
     */
    public static function saveSqlReload(Erra_Fields_Base_Object $field) {
        Erra_System_Factory::saveField($field, 'SQL');
        return 'RELOAD';
    }

    /**
     * AdminAction::saveSqlReloadNoMessage() - Saves a field in database and reloads page
     *
     * @param mixed $field
     * @return
     */
    public static function saveSqlReloadNoMessage(Erra_Fields_Base_Object $field) {
        Erra_System_Factory::saveField($field, 'SQL');
        return 'RELOAD';
    }

    /**
     * AdminAction::saveSession() - Saves a field in session
     *
     * @param mixed $field
     * @return
     */
    public static function saveSession(Erra_Fields_Base_Object $field) {
        $field->setMessage(Erra_Utils_Tools::message('success', __('Data saved in session')));
        Erra_System_Factory::saveField($field, 'SESSION');
        return 'FORM_REFRESH_FIELD';
    }

    public static function REFRESH_FIELD_LIST($postArray, $message = null, $objectList = null) {
        $action = $postArray['method'];
        $messageInfo = '';
        if (is_array($message) && count($message) == 1) {
            $key = array_keys($message);
            $messageInfo = ':' . $key[0] . ' => ' . $message[$key[0]];
        }
        if (!is_null($objectList) && is_array($objectList) && !count($objectList)) {
            $messageInfo = ':error => ' . __('Please select items');
        }
        return 'FORM_REFRESH_FIELD_LIST => ' . $action . $messageInfo;
    }

    public static function refreshList() {
        $postArray = Erra_System_FormRenderer::getFieldPostData();
        $fieltEltName = $postArray['object_id'];
        $fieltFacotryId = $postArray['object_class'];

        return self::REFRESH_FIELD_LIST($postArray);
    }

    /**
     * Erra_System_Action::editInPlace() - Enables edit in place mode
     *
     * @param mixed $field
     * @return
     */
    public static function editInPlace() {
        $postArray = Erra_System_FormRenderer::getFieldPostData();
        $action = $postArray['method'];
        return 'EDIT_IN_PLACE => ' . $action;
    }

    public static function changePosition() {
        $postArray = Erra_System_FormRenderer::getFieldPostData();
        $fieltEltName = $postArray['object_id'];
        $fieltFacotryId = $postArray['object_class'];
        $table = $_POST['table_manip'];
        $currentId = $_POST['current_id'];
        $newId = $_POST['new_id'];

        $qrow = Erra_Core_DatabasePdo::SELECT('SELECT MAX(id) as id FROM ' . $table);
        $result = $qrow->fetch();
        $maxId = $result->id + 777;

        Erra_Core_DatabasePdo::EXECUTE('UPDATE ' . $table . ' SET id=' . $maxId . ' WHERE id=' . $newId);
        Erra_Core_DatabasePdo::EXECUTE('UPDATE ' . $table . ' SET id=' . $newId . ' WHERE id=' . $currentId);
        Erra_Core_DatabasePdo::EXECUTE('UPDATE ' . $table . ' SET id=' . $currentId . ' WHERE id=' . $maxId);

        return self::REFRESH_FIELD_LIST($postArray);
    }

    public static function editListInPlace() {
        $postArray = Erra_System_FormRenderer::getFieldPostData();
        $action = $postArray['method'];
        return 'EDIT_IN_PLACE => ' . $action;
    }

    /**
     * Erra_System_Action::deleteInstance() - Deletes an instance for an array field
     *
     * @return
     */
    public static function deleteInstance() {
        $postArray = Erra_System_FormRenderer::getFieldPostData();
        $fieltEltName = $postArray['object_id'];
        $fieltFacotryId = $postArray['object_class'];
        $buildArgs = !empty($postArray['build_args']) ? Erra_Serialization_SerializerJson::unserializeRaw(html_entity_decode($postArray['build_args'])) : null;
        $object = Erra_System_Factory::getFieldObject($fieltFacotryId, null, 'CREATE', null, $buildArgs);
        $table = $object->getTableName();
        $queryRes = Erra_Core_DatabasePdo::EXECUTE('DELETE FROM ' . $table . ' WHERE object_class="' . $fieltFacotryId . '" AND id=' . $postArray['id']);

        return self::REFRESH_FIELD_LIST($postArray, array('error' => __('Item deleted')));
    }

    /**
     * Erra_System_Action::addInstance() - Adds an instance for an array field
     *
     * @return
     */
    public static function addInstance() {
        $postArray = Erra_System_FormRenderer::getFieldPostData();
        $fieltEltName = $postArray['object_id'];
        $fieltFacotryId = $postArray['object_class'];
        $buildArgs = !empty($postArray['build_args']) ? Erra_Serialization_SerializerJson::unserializeRaw(html_entity_decode($postArray['build_args'])) : null;
        $nullObject = Erra_System_Factory::getFieldObject($fieltFacotryId, null, 'CREATE', null, $buildArgs);


        Erra_System_Factory::saveField($nullObject, 'SQL');

        return self::REFRESH_FIELD_LIST($postArray, array('success' => __('Item added')));
    }

    /**
     * Erra_System_Action::addInstance() - Adds an instance for an array field
     *
     * @return
     */
    public static function searchModule() {
        $postArray = Erra_System_FormRenderer::getFieldPostData();
        $fieltEltName = $postArray['object_id'];
        $fieltFacotryId = $postArray['object_class'];
        $postArray['method'] = $postArray['old_method'];

        // Erra_Persistance_Session::set('[@message@]' . $field->getObjectId(), $field->getMessage());
        return self::REFRESH_FIELD_LIST($postArray, array('info' => __('Search done with success')));
    }

    /**
     * Erra_System_Action::validate() - Validates a field
     *
     * @param mixed $field
     * @param mixed $condition
     * @param mixed $message
     * @param mixed $errorStack
     * @return
     */
    public static function validate($field, $condition, $message, &$errorStack) {
        if ($condition == false) {
            if (is_array($message) && count($message) == 1) {
                $key = array_keys($message);
                $message = Erra_Utils_Tools::message($key[0], $message[$key[0]]);
            }
            $field->setMessage($message);

            $errorStack = true;
        }
    }

    /**
     * Erra_System_Action::uploadImage() - Uploads in image
     *
     * @param mixed $field
     * @return
     */
    public static function uploadImage(&$field) {
        $subFields = $field->getSubFields();
        if (is_array($subFields) && count($subFields) > 0) {
            foreach ($subFields as $subField) {
                self::_uploadImage($subField);
                // We check if image is in subinstance
                $instances = $subField->getAllInstances();
                foreach ($instances as $subInstance) {
                    self::_uploadImage($subInstance);
                    // We check at deth level 3 (the last technically displayable)
                    $subFieldsLevel3 = $subInstance->getSubFields();

                    foreach ($subFieldsLevel3 as $subFieldLevel3) {
                        self::_uploadImage($subFieldLevel3);
                    }
                }
            }
        }
    }

    /**
     * Erra_System_Action::_uploadImage() - Uploads an image
     *
     * @param mixed $field
     * @return
     */
    public static function _uploadImage(&$field) {
        $class = get_class($field);

        $result = false;
        $allowed_ext = is_null($field->allowed_ext) ? 'jpg|png|gif' : $field->allowed_ext;
        $allowed_ext_str = implode(', ', explode('|', $allowed_ext));
        if ($class == 'Erra_Fields_Image' || $class == 'Erra_Fields_ImageBank') {
            $result = $field->saveUploaded($field->dir . '/_FILENAME_', $allowed_ext, 'The file _FILENAME_ is not valid');
            if ($result === false)
                $field->setMessage('[error] ' . __('File upload failed ! Allowed extensions are') . ' ' . $allowed_ext_str);
        } else if ($class == 'Erra_Fields_File') {
            $result = $field->saveUploaded($field->dir . '/_FILENAME_', $field->allowed_ext, 'The file _FILENAME_ is not valid');
            if ($result === false)
                $field->setMessage('[error] ' . __('File upload failed ! Allowed extensions are') . ' ' . $allowed_ext_str);
        }

        return $result;
    }

    /**
     * AdminAction::saveLocale() - Saves translation data files
     *
     * @param mixed $field
     * @return
     */
    public static function saveLocale(Erra_Fields_Base_Object $field) {
        $langs = Erra_Core_Locale::getAvailableLangs();
        $langKeys = array_keys($langs);
        $default_lang = $langKeys[0];
        $langFiles = array();
        $traduce_file = $field->getBuildArgs();
        FB::log($traduce_file);
        foreach ($langKeys as $aLang) {
            $basename = "[$aLang] " . strtolower(basename($traduce_file));
            $langFiles[$aLang] = '/* Partial language file ' . $basename . ' created the ' . date('d-m-Y') . ' @ ' . date('H') . 'h' . date('i') . ' */' . "\n\n";
        }
        foreach ($field->getSubFields() as $aSubField) {
            if (get_class($aSubField) == 'Erra_Fields_Text') {
                $keyId = 'key_' . $aSubField->getObjectId();
                $needle = $field->$keyId->value;
                foreach ($langKeys as $aLang) {
                    // Language by default, then english, then display error
                    if ($aSubField->$aLang->value != null) {
                        $langFiles[$aLang] .= '$GLOBALS["__l10n"]["' . $needle . '"] = "' . $aSubField->$aLang->value . '";' . "\n";
                    } else if ($aLang == $default_lang) {
                        $country = ucfirst(strtolower(Erra_Core_Locale::getCountry($aLang)));
                        $langFiles[$aLang] .= '$GLOBALS["__l10n"]["' . $needle . '"] = "' . $needle . '";' . "\n";
                    } else {
                        $aLangCountry = ($aLang == 'en') ? 'us' : $aLang;
                        $country = ucfirst(strtolower(Erra_Core_Locale::getCountry($aLangCountry)));
                        $langFiles[$aLang] .= '$GLOBALS["__l10n"]["' . $needle . '"] = "[' . __('missing translation') . ' !]";' . "\n";
                    }
                }
            }
        }
        $nbFileGenerated = 0;
        foreach ($langKeys as $aLang) {
            $langFiles[$aLang] .= "\n";
            if (strlen($traduce_file) > 0) {
                $basename = strtolower(basename($traduce_file));
                file_put_contents(DOCUMENT_ROOT . '/application/L10n/translation.' . $aLang . '.' . $basename, security_restore_output($langFiles[$aLang]));
                $nbFileGenerated++;
            }
        }


        // Regenerate the root translation file by merging all partial translation files
        // to create translation.[CODE].lang.php file.
        if ($nbFileGenerated == count($langKeys)) {
            $files = Erra_Core_File::spl_scanRecursiveDir(DOCUMENT_ROOT . '/application/L10n');
            $translation_root_files = array();
            foreach ($langKeys as $aLang) {
                if (!isset($translation_root_files[$aLang])) {
                    $translation_root_files[$aLang] = '<?php' . "\n\n";
                    $translation_root_files[$aLang] .= '/* Language file created the ' . date('d-m-Y') . ' @ ' . date('H') . 'h' . date('i') . ' */' . "\n\n";
                }
                foreach ($files as $partial_traduce_filename) {
                    if (strstr($partial_traduce_filename, "translation.$aLang.") !== false
                            && basename($partial_traduce_filename) != "translation.$aLang.lang.php") {
                        $translation_root_files[$aLang] .= "\n" . file_get_contents($partial_traduce_filename);
                    }
                }
                $translation_root_files[$aLang] .= '?>' . "\n";
                file_put_contents(DOCUMENT_ROOT . '/application/L10n/translation.' . $aLang . '.lang.php', $translation_root_files[$aLang]);
            }
            Erra_Utils_Tools::message('success', __('Traduction file based on ') . $basename . (' done with success'), 'saveLocale');
        } else {
            Erra_Utils_Tools::message('error', __('Traduction files based on ') . $basename . (' creation failed'), 'saveLocale');
        }
        return 'RELOAD';
    }

    /**
     * AdminAction::saveEditorFile() - Saves a view, layout or object coded files
     *
     * @param mixed $field
     * @return
     */
    public static function saveEditorFile(Erra_Fields_Base_Object $field) {
        if ($field->changeFile->value == 1) {
            $field->setMessage(Erra_Utils_Tools::message('info', __('File loaded with success')));
            $field->changeFile->setValue(0);
        } else {
            $fileName = DOCUMENT_ROOT . Base_FileEditorObject::url_to_filepath($field->currentFile->getRawData());
            $contents = security_restore_output($field->editareaZone->getRawData());
            if (file_put_contents($fileName, $contents) !== FALSE) {
                $field->setMessage(Erra_Utils_Tools::message('success', __('File saved with success')));
            } else {
                $field->setMessage(Erra_Utils_Tools::message('warning', __('File couldn\'t be saved')));
            }
        }
        return 'FORM_REFRESH_FIELD';
    }

}

?>